import {getRouters} from "@/api/menu";
import {constantRouterMap} from "@/router/routers";
import Main from '@/components/main'
export function generateIndexRouter(data){
  let indexRouter=[
    {
      path: "/",
      name: "_home",
      redirect: "/home",
      component: Main,
      meta: { hideInMenu: true, notCache: true },
      children: [
        {
          path: "/home",
          name: "home",
          icon: "md-home",
          meta: {
            hideInMenu: true,
            title: "首页",
            notCache: true,
          },
          component: () => import("@/components/single-page/home/home")
        },
      ]
    },
    ...filterAsyncRouter(data)
    // , {
    //   path: "*", redirect: "/404", hidden: true
    // }
  ]
  return indexRouter;
}
function filterAsyncRouter(asyncRouterMap) {
  return asyncRouterMap.filter(route => {
    if (route.component) {
      // Layout组件特殊处理
      if (route.component === 'Main') {
        route.component = Main
      } else {
        route.component = loadView(route.component)
      }
    }
    if (route.children != null && route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children)
    }
    return true
  })
}
export const loadView = (view) => { // 路由懒加载
  return () => import(`@/view/${view}.vue`)
}
const permission = {
  state: {
    routers: constantRouterMap,
    addRouters: []
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers
      state.routers = constantRouterMap.concat(routers)
    }
  },
  getters:{
    menuList: state => state.addRouters,
  },
  actions: {
    GenerateRoutes ({ commit },) {
      return new Promise(resolve => {
        getRouters().then(res=>{
          if(res.code===200){
            const accessedRouters = generateIndexRouter(res.data)
            console.log(accessedRouters)
            commit('SET_ROUTERS', accessedRouters)
            resolve()
          }
        })
      })
    }
  }
}
export default permission;
